package com.ycsj.goldmedalnewconcept.common.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.ycsj.common.adapter.VpCommonAdapter;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.manager.MediaPlayerManager;
import com.ycsj.common.utils.ArithUtil;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.SPUtil;
import com.ycsj.common.view.vp.CanotSlidingViewpager;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.Constants;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.bean.AnswerInfo;
import com.ycsj.goldmedalnewconcept.common.bean.TopicInfo;
import com.ycsj.goldmedalnewconcept.common.fragment.AnswerFragment;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.TestTimeCountUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

public class FollowReadDetailsActivity extends BaseActivity implements OnPageChangeListener {

    @BindView(R.id.tv_title)
    TextView tvTitle;

    // 外层的加载布局
    @BindView(R.id.rl_loading)
    RelativeLayout llLoading;

    // 内容布局
    @BindView(R.id.ll_content)
    LinearLayout llContent;

    // 进度条对象
    @BindView(R.id.pb)
    ProgressBar pb;

    // 显示进度条的文字
    @BindView(R.id.tv_pb)
    TextView tvPb;

    // 返回
    @BindView(R.id.iv_back)
    ImageView lvBack;

    // ViewPager对象
    @BindView(R.id.vp)
    CanotSlidingViewpager vp;

    // 获取传递过来的班级lESSON_ID
    private String lessonId;

    // 填充Vp的Framgent集合
    private List<Fragment> mFragments;

    // ViewPager的适配器
    private VpCommonAdapter adapter;

    // 记录当前Vp的位置
    private int vpPos = 0;

    // 用户名
    private String account;

    // 用户角色
    private String role;

    //单元号
    private String unit;

    //token
    private String apptoken;

    // 用户角色
    private List<Integer> currentItemList;
    private List<TopicInfo.QuestionListBean> questions;

    //ViewPager滚动的标识
    public static final int VPSCROLL = 0x710;

    //当前界面关闭
    public static final int FINISH = 0x720;

    //计时的ID
    private String rid;


    /**
     * 跳转到当前界面的方法
     *
     * @param context
     * @param lESSON_ID
     */
    public static void goActivity(Context context, String lESSON_ID, String unit) {
        Intent it = new Intent(context, FollowReadDetailsActivity.class);
        it.putExtra("lESSON_ID", lESSON_ID);
        it.putExtra("unit", unit);
        context.startActivity(it);
    }

    @Override
    protected int getContentLayout() {
        return R.layout.activity_follow_details;
    }

    @Override
    protected void init() {

        initStateBar();

        // 获取年级ID和名称
        initData();

        //初始化状态
        initState();

        //初始化参数
        initParams();

        // 设置初始数据
        httpData();

    }


    /**
     * 获取年级ID和年级名称的方法
     */
    private void initData() {
        lessonId = getIntent().getStringExtra("lESSON_ID");
        unit = getIntent().getStringExtra("unit");
        currentItemList = new ArrayList<>();
    }


    /**
     * 初始化状态
     */
    private void initState() {
        llContent.setVisibility(View.GONE);
        llLoading.setVisibility(View.VISIBLE);
        tvTitle.setText("课文跟读");
        vp.setScrollble(false);
        vp.addOnPageChangeListener(this);
    }

    /**
     * 初始化请求参数
     */
    private void initParams() {
        account = AccountUtils.getAccount(this);
        role = AccountUtils.getRole(this);
        apptoken = AccountUtils.getToken(this);
    }

    /**
     * 通过请求服务器获取模块数据
     */
    private void httpData() {

        Map<String, String> map = new HashMap<>();
        map.put("lessonid", lessonId);
        map.put("type", "5");
        map.put("acc", account);
        map.put("done", "0");
        map.put("role", role);
        map.put("token1", apptoken);
        map.put("platform", "2");

        HttpUtils.get(HttpAddress.FOLLOWREAD, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                llLoading.setVisibility(View.GONE);
                ToastUtils.showShort(BaseApplication.ERROR);
            }

            @Override
            public void onResponse(String response, int id) {
                llLoading.setVisibility(View.GONE);

                if (!TextUtils.isEmpty(response)) {
                    TopicInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, TopicInfo.class);
                    } catch (Exception e) {
                        ToastUtils.showShort(Constants.PARSEDATAERROR);
                    }

                    if (null != info && "200".equals(info.getState())) {
                        //取出所有题的数据
                        questions = info.getQuestion_list();

                        if (null == questions || questions.size() == 0) {
                            //证明没有问题
                            ToastUtils.showShort("暂无数据返回");
                        } else {
                            //有问题
                            llContent.setVisibility(View.VISIBLE);

                            //设置Vp的数据
                            setVpData();
                        }
                    } else {
                        ToastUtils.showShort(BaseApplication.STATEERROE + info.getState());
                    }

                } else {
                    ToastUtils.showShort(Constants.EMPTY);
                }
            }
        });
    }

    /**
     * 设置Vp的数据
     */
    private void setVpData() {
        //创建填充的Fragment集合
        mFragments = new ArrayList<>();

        //用于保存所有题目的录音和详情的集合,存放于sp中,用于最后一个列表展示页面进行展示
        List<AnswerInfo> answerDatas = new ArrayList<>();

        for (int i = 0; i < questions.size(); i++) {
            AnswerFragment answerFragment = null;

            if (i == questions.size() - 1) {
                //最后一页
                answerFragment = AnswerFragment.newInstance(questions.get(i), i, questions.size(), lessonId, true, unit);
            } else {
                //不是最后一页
                answerFragment = AnswerFragment.newInstance(questions.get(i), i, questions.size(), lessonId, false, unit);
            }
            mFragments.add(answerFragment);

            // 设置最后的列表展示数据的默认值
            AnswerInfo answerInfo = new AnswerInfo();

            answerInfo.audioPath = "";
            answerInfo.path = questions.get(i).getAudio();
            answerInfo.isPlay = false;
            answerInfo.isRecord = false;
            answerInfo.questionContent = questions.get(
                    i).getDialogue();
            answerInfo.score = 0;
            answerInfo.isShowScore = true;
            answerInfo.postion = i;
            answerInfo.lessionId = lessonId;
            answerInfo.isAllowTouch = true;
            answerInfo.isEnabled = true;
            answerInfo.question_id = questions.get(i)
                    .getQuestion_id();
            answerInfo.question_type = questions.get(i)
                    .getQuestion_type();

            // 保存答案信息
            answerDatas.add(answerInfo);
        }

        //将最后列表展示的集合数据存放于SP中保存
        SPUtil.put(this, lessonId, GsonUtil.listToJson(answerDatas));

        adapter = new VpCommonAdapter(getSupportFragmentManager(), mFragments);
        vp.setAdapter(adapter);
        vp.setOffscreenPageLimit(questions.size());

        //设置默认进度条
        pb.setProgress(ArithUtil.bs(1, questions.size()));
        tvPb.setText("1/" + mFragments.size());
    }

    /**
     * 滚动监听事件
     *
     * @param position
     * @param positionOffset
     * @param positionOffsetPixels
     */
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int pos) {

        // 改变记录当前Vp的位置
        vpPos = pos;
        // 页面选中的时候需要改变顶部的进度条的进度,注意:这个pos是从0开始算的
        pb.setProgress(ArithUtil.bs(pos + 1, mFragments.size()));
        tvPb.setText((pos + 1) + "/" + mFragments.size());
        int j = 0;
        for (int i = 0; i < currentItemList.size(); i++) {
            if (pos == currentItemList.get(i)) {
                j = 1;
            }
        }
        if (j != 1) {
            currentItemList.add(pos);
        }
        if (pos < currentItemList.size() - 1) {
            vp.setScrollble(true);
        } else {
            vp.setScrollble(false);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * 点击事件
     *
     * @param v
     */
    @OnClick({R.id.iv_back})
    public void clickEvent(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                //返回
                finish();
                break;
        }
    }

    /**
     * 事件处理
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo) {
            if (VPSCROLL == busInfo.type) {
                // 进行翻页处理
                vp.setCurrentItem(vpPos + 1);
            } else if (FINISH == busInfo.type) {
                //关闭当前页面
                finish();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        TestTimeCountUtil.startTime(this, "9", String.valueOf(lessonId).substring(0, 4), lessonId, new TestTimeCountUtil.onSuccessListener() {
            @Override
            public void onSuccess(String infoRid) {
                rid = infoRid;
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        TestTimeCountUtil.stopTime(this, rid);
    }

    /**
     * 生命周期中置空播放器对象
     */
    @Override
    protected void onDestroy() {
        MediaPlayerManager.getInstance().stop();
        super.onDestroy();
    }
}
